package com.example.libary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.libary.entity.BookCategory;
import com.example.libary.mapper.BookCategoryMapper;
import com.example.libary.service.BookCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图书分类服务实现类
 */
@Service
public class BookCategoryServiceImpl extends ServiceImpl<BookCategoryMapper, BookCategory> implements BookCategoryService {

    @Override
    public List<BookCategory> list(String name) {
        LambdaQueryWrapper<BookCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), BookCategory::getName, name)
                .orderByAsc(BookCategory::getParentId)
                .orderByAsc(BookCategory::getOrderNum);
        return list(wrapper);
    }

    @Override
    public List<BookCategory> tree() {
        // 获取所有分类
        List<BookCategory> allCategories = list();
        
        // 根据parentId分组
        Map<Long, List<BookCategory>> parentMap = allCategories.stream()
                .collect(Collectors.groupingBy(BookCategory::getParentId));
        
        // 获取一级分类
        List<BookCategory> rootCategories = parentMap.getOrDefault(0L, new ArrayList<>());
        
        // 递归设置子分类
        rootCategories.forEach(category -> setChildren(category, parentMap));
        
        return rootCategories;
    }

    /**
     * 递归设置子分类
     */
    private void setChildren(BookCategory parent, Map<Long, List<BookCategory>> parentMap) {
        List<BookCategory> children = parentMap.getOrDefault(parent.getId(), new ArrayList<>());
        parent.setChildren(children);
        children.forEach(child -> setChildren(child, parentMap));
    }

    @Override
    public List<BookCategory> listByParentId(Long parentId) {
        LambdaQueryWrapper<BookCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookCategory::getParentId, parentId)
                .orderByAsc(BookCategory::getOrderNum);
        return list(wrapper);
    }

    @Override
    public boolean checkNameExists(String name, Long id) {
        LambdaQueryWrapper<BookCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookCategory::getName, name)
                .ne(id != null, BookCategory::getId, id);
        return count(wrapper) > 0;
    }
} 